/*
 * @Author: Zhang Kai
 * @Date: 2022-05-26 14:36:05
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-06 14:47:52
 * @FilePath: /metricsx-standard-ui/src/views/indexManage/frontSettings/components/classManage/index.tsx
 */
import {
  defineComponent,
  onMounted,
  PropType,
  reactive,
  watch,
  ref,
  nextTick
} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import API from '@/services';
import Table from '@/components/Table/index';
import GroupTree from '@/components/GroupTree';
import { Search } from '@element-plus/icons-vue';
import './index.scss';
const classManage = defineComponent({
  name: 'classManage',
  props: {
    keys: {
      type: Number,
      default: () => ''
    }
  },
  setup: (props, { slots, attrs, emit }) => {
    // 获取api
    const {
      metricsGroup: {
        deleteMetricsGroupById,
        postMetricsGroup,
        putMetricsGroup,
        getMetricsGroupRootByRootId,
        getMetricsGroupRootDisplay,
        getMetricsGroupListRoot,
        getMetricsGroupMetricsList,
        postMetricsGroupMetricsAdd,
        postMetricsGroupRoot
      }
    } = API;

    /* 指标表格cloumn */
    const classManageColumn: any = ref([
      {
        type: 'selection',
        selectable: (row: any) => !row.disabled
      },
      {
        prop: 'metricsId',
        label: 'ID'
      },
      {
        prop: 'metricsName',
        label: '名称'
      },
      {
        prop: 'businessMeaning',
        label: '业务含义'
      }
    ]);

    /* 分类表格cloumn */
    const tableColumn: any = ref([
      {
        prop: 'name',
        label: '分类'
      },
      {
        prop: 'number',
        label: '当前指标数'
      },
      {
        prop: 'createBy',
        label: '创建人'
      },
      {
        label: '是否展示',
        default: ({ row }: any) => (
          <>
            <el-switch
              active-value={1}
              inactive-value={0}
              onChange={() => {
                isShowApi(row);
              }}
              v-model={row.display}
            />
          </>
        )
      },
      {
        label: '操作',
        default: ({ row }: any) => (
          <>
            <el-button
              type="text"
              onClick={() => {
                visible.value = true;
                isShow.value = true;
                editInfo.value = row;
                indexState.value = 2;
                MetricsGroupMetricsList.pageNum = 1;
                metricsGroupMetricsListApi();
              }}
            >
              查看
            </el-button>
            <el-button
              type="text"
              onClick={async () => {
                isEdit.value = true;
                visible.value = true;
                editInfo.value = row;
                indexState.value = 1;
                MetricsGroupMetricsList.pageNum = 1;
                metricsCheck();
              }}
            >
              编辑
            </el-button>
            <el-button type="text" onClick={() => ClassManageDel(row.id)}>
              删除
            </el-button>
          </>
        )
      }
    ]);

    /* 是否为编辑状态 */
    const isEdit = ref(false);

    /* 抽屉状态 */
    const visible = ref(false);

    /* 分类表格loading */
    const listLoading = ref(false);

    /* 指标表格loading */
    const classManageLoading = ref(false);

    /* 是否为查看状态 */
    const isShow = ref(false);

    /* 筛选指标的名称 */
    const searchName = ref('');

    /* 分类ID */
    const groupId = ref();

    // 分组key
    const groupKey = ref(1);

    /* 创建分组名称 */
    const createName = ref('');

    /* 创建分组Popover */
    const visiblePopover = ref(false);

    /* 编辑当前行信息 */
    const editInfo: any = ref({});

    /* 加入左侧的指标list */
    const metricsOptDTOS: any = ref([]);

    /**
     * 编辑/查看状态
     * 1 编辑
     * 2 查看
     */
    const indexState = ref(1);

    /* 当前选中的是否为叶子节点 */
    const isLast = ref(false);

    /* 指标表格ref */
    const tableRef = ref();

    /* 指标list */
    const MetricsGroupMetricsList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10
    });

    /* 分类管理list */
    const classManageList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10
    });

    const ClassManageDel = async (rootId: number) => {
      ElMessageBox.alert('', '是否确认删除该分类?', {
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'message-box-del'
      })
        .then(async () => {
          try {
            const { code } =
              await API.metricsGroup.deleteMetricsGroupRootByRootId({ rootId });
            if (code === 200) {
              getClassManageList();
              ElMessage.success('删除成功');
            }
          } catch (error) {
            console.log(error);
            ElMessage.error('删除失败');
          }
        })
        .catch(() => {
          ElMessage.info('取消删除');
        });
    };

    /* 隐藏显示接口 */
    const isShowApi = async (row: any) => {
      try {
        let { code } = await getMetricsGroupRootDisplay({
          display: row.display,
          rootId: row.id
        });
        if (code === 200) {
          getClassManageList();
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 分类 list */
    const getClassManageList = async () => {
      try {
        listLoading.value = true;
        const { pageNum, pageSize } = classManageList;
        const { code, data }: any = await getMetricsGroupListRoot({
          pageNum,
          pageSize
        });
        if (code === 200 && Array.isArray(data?.list)) {
          classManageList.list = data?.list;
          classManageList.total = data?.total;
        }
      } catch (error) {
        console.log(error);
      } finally {
        listLoading.value = false;
      }
    };

    /* 指标list */
    const metricsGroupMetricsListApi = async () => {
      try {
        classManageLoading.value = true;
        const { pageNum, pageSize } = MetricsGroupMetricsList;
        const { code, data }: any = await getMetricsGroupMetricsList({
          pageNum,
          pageSize,
          rootId: editInfo.value?.id,
          mode: indexState.value,
          groupId: groupId.value || editInfo.value?.id,
          metricsName: searchName.value
        });
        if (code === 200 && Array.isArray(data?.list)) {
          MetricsGroupMetricsList.list = data?.list;
          MetricsGroupMetricsList.total = data?.total;
          metricsOptDTOS.value = [];
        }
      } catch (error) {
        console.log(error);
      } finally {
        classManageLoading.value = false;
      }
    };

    const handleClose = () => {
      visible.value = false;
      isEdit.value = false;
      isShow.value = false;
      groupId.value = '';
      searchName.value = '';
      getClassManageList();
    };

    /* 分类关联的指标勾选 */
    const metricsCheck = async () => {
      await metricsGroupMetricsListApi();
      MetricsGroupMetricsList.list.forEach((j: any) => {
        j.check && tableRef?.value.toggleRowSelection(j, true);
      });
      addClassifyList(MetricsGroupMetricsList.list);
    };

    /* 加入左侧 */
    const pushClassify = async () => {
      if (!metricsOptDTOS.value.length) {
        ElMessage.warning('至少选择一个指标');
        return;
      }
      if (!groupId.value) {
        ElMessage.warning('请选择要加入的分类');
        return;
      }
      if (!isLast.value) {
        ElMessage.warning('请加入到叶子节点');
        return;
      }
      try {
        let { code } = await postMetricsGroupMetricsAdd({
          groupId: groupId.value,
          metricsOptDTOS: metricsOptDTOS.value,
          rootId: editInfo.value?.id
        });
        if (code === 200) {
          ElMessage.success('加入成功');
          groupKey.value++;
          groupId.value = '';
          metricsCheck();
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 创建分类 */
    const createClassify = async () => {
      if (!createName.value) {
        ElMessage.warning('请输入分类名称');
        return;
      }
      try {
        let { code } = await postMetricsGroupRoot({
          name: createName.value
        });
        if (code === 200) {
          ElMessage.success('创建分类成功');
          visiblePopover.value = false;
          createName.value = '';
          getClassManageList();
        }
      } catch (error) {
        console.log(error);
      }
    };

    const addClassifyList = (arr: any) => {
      arr?.forEach((v: any) => {
        const index = metricsOptDTOS.value.findIndex(
          (j: any) => v.metricsId === j.metricsId
        );
        if (index === -1) {
          if (v.check && !v.disabled) {
            metricsOptDTOS.value.push({
              metricsId: v.metricsId,
              check: v.check
            });
          }
        } else {
          metricsOptDTOS.value[index] = {
            metricsId: v.metricsId,
            check: v.check
          };
        }
      });
    };

    onMounted(() => {
      getClassManageList();
    });

    watch(
      () => props?.keys,
      () => {
        getClassManageList();
      }
    );

    watch(
      () => indexState.value,
      (state) => {
        if (state === 2) {
          classManageColumn.value.splice(0, 1);
        } else if (state === 1) {
          classManageColumn.value.unshift({
            type: 'selection'
          });
        }
      }
    );

    return () => {
      return (
        <div class="classManage-container">
          <el-popover
            visible={visiblePopover.value}
            placement="bottom-end"
            trigger="click"
            popper-class="classManage-create-container"
            v-slots={{
              reference: () => (
                <div class="classManage-createBtn">
                  <el-button
                    onClick={() => (visiblePopover.value = true)}
                    type="primary"
                  >
                    创建分类
                  </el-button>
                </div>
              )
            }}
          >
            <>
              <el-input
                placeholder="请输入分类名称"
                v-model={createName.value}
              />
              <div class="classManage-create-btn">
                <el-button
                  onClick={() => {
                    visiblePopover.value = false;
                    createName.value = '';
                  }}
                >
                  取消
                </el-button>
                <el-button onClick={createClassify} type="primary">
                  创建
                </el-button>
              </div>
            </>
          </el-popover>

          <Table
            v-loading={listLoading.value}
            data={classManageList.list}
            column={tableColumn.value}
            onPageCurrentChange={(page: number) => {
              classManageList.pageNum = page;
              getClassManageList();
            }}
            onPageSizeChange={(size: number) => {
              classManageList.pageNum = 1;
              classManageList.pageSize = size;
              getClassManageList();
            }}
            pagination={{
              total: classManageList.total * 1,
              currentPage: classManageList.pageNum,
              pageSize: classManageList.pageSize
            }}
          />

          <el-drawer
            custom-class="classManage-drawer"
            v-model={visible.value}
            title={
              isEdit.value ? '编辑分类' : isShow.value ? '查看分类' : '创建分类'
            }
            close-on-click-modal={false}
            append-to-body={true}
            direction="rtl"
            before-close={handleClose}
            onClosed={handleClose}
            lock-scroll={false}
          >
            {visible.value && (
              <div class="createClassManage">
                <div class="createClassManage-left">
                  <GroupTree
                    isOperate={isShow.value ? false : true}
                    titles={editInfo.value?.name}
                    groupKey={groupKey.value}
                    rootId={editInfo.value?.id}
                    listFn={() =>
                      getMetricsGroupRootByRootId({
                        rootId: editInfo.value?.id
                      })
                    }
                    delFn={deleteMetricsGroupById}
                    reNameFn={putMetricsGroup}
                    addFn={postMetricsGroup}
                    onGetTreeNode={async (v: any) => {
                      if (v.id === 'new') return;
                      groupId.value = v.id;
                      isLast.value = v.last;
                      metricsCheck();
                    }}
                  ></GroupTree>
                </div>
                <div class="createClassManage-right">
                  {!isShow.value ? (
                    <div class="createClassManage-right-title">
                      <el-input
                        v-model={searchName.value}
                        placeholder="请输入名称搜索"
                        suffix-icon={Search}
                        style={{ width: '40%' }}
                        onChange={metricsCheck}
                      />
                      <el-button onClick={pushClassify} type="primary">
                        &lt; 加入左侧
                      </el-button>
                    </div>
                  ) : undefined}

                  <Table
                    v-loading={classManageLoading.value}
                    data={MetricsGroupMetricsList.list}
                    tableRef={tableRef}
                    column={classManageColumn.value}
                    onSelectAll={(selection: any) => {
                      if (selection.length) {
                        selection?.forEach((v: any) => (v.check = true));
                      } else {
                        selection = metricsOptDTOS.value?.forEach(
                          (v: any) => (v.check = false)
                        );
                      }
                      addClassifyList(
                        selection.filter((v: any) => !v.disabled)
                      );
                    }}
                    onSelect={async (selection: any, row: any) => {
                      row.check = row.check ? false : true;
                      const arr: any = [];
                      arr.push(row);
                      await addClassifyList(arr);
                    }}
                    onPageCurrentChange={async (page: number) => {
                      MetricsGroupMetricsList.pageNum = page;
                      metricsCheck();
                    }}
                    pagination={{
                      layout: ' prev, pager, next, jumper',
                      total: MetricsGroupMetricsList.total * 1,
                      currentPage: MetricsGroupMetricsList.pageNum,
                      pageSize: MetricsGroupMetricsList.pageSize
                    }}
                  />
                </div>
                {isEdit.value ? (
                  <div class="footer-btn">
                    <el-button onClick={handleClose} type="primary">
                      确定
                    </el-button>
                  </div>
                ) : undefined}
              </div>
            )}
          </el-drawer>
        </div>
      );
    };
  }
});

export default classManage;
